package com.nefu.editor.web;

import com.nefu.editor.common.EdiException;
import com.nefu.editor.common.ErrorMessage;
import com.nefu.editor.common.RestData;
import com.nefu.editor.common.util.JsonUtil;
import com.nefu.editor.common.util.TokenUtil;
import com.nefu.editor.core.model.User;
import com.nefu.editor.core.model.Vo.UserVo;
import com.nefu.editor.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author chenchenT
 * @date : 18-11-12
 * @since : java 8
 */
@CrossOrigin(origins = "*", allowCredentials = "true", allowedHeaders = "*")
@RestController
public class LoginApi {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final UserService userService;

    @Autowired
    public LoginApi(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public RestData postLogin(@RequestBody User user) {
        logger.info("POST postLogin : " + JsonUtil.getJsonString(user));
        try {
            Map<String, Object> data = userService.postLogin(user);
            return new RestData(data);
        } catch (EdiException e) {
            return new RestData(1, e.getMessage());
        }
    }

    @RequestMapping(value = "/change-password", method = RequestMethod.PUT)
    public RestData changePassword(@RequestBody UserVo userVo, HttpServletRequest request) {
        logger.info("changePassword : " + JsonUtil.getJsonString(userVo));
        User currentUser = TokenUtil.getUserByToken(request);
        if (null != currentUser) {
            try {
                boolean success= userService.changePassword(userVo);
                return  new RestData(success);
            } catch (EdiException e) {
                return new RestData(1, e.getMessage());
            }
        } else {
            return new RestData(2, ErrorMessage.PLEASE_RELOGIN);
        }
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public RestData register(@RequestBody User user, HttpServletRequest request) {
        logger.info("changePassword : " + JsonUtil.getJsonString(user));
        User currentUser = TokenUtil.getUserByToken(request);
        if (null != currentUser) {
            try {
                boolean success= userService.register(user);
                return  new RestData(success);
            } catch (EdiException e) {
                return new RestData(1, e.getMessage());
            }
        } else {
            return new RestData(2, ErrorMessage.PLEASE_RELOGIN);
        }
    }

}
